package edu.zut.hys.user.controller;

import edu.zut.hys.base.entity.User;
import edu.zut.hys.base.entity.UserRole;
import edu.zut.hys.base.enums.ResponseCode;
import edu.zut.hys.base.mapper.UserMapper;
import edu.zut.hys.base.mapper.UserRoleMapper;
import edu.zut.hys.base.service.UserService;
import edu.zut.hys.base.vo.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author Hys
 * Date 2022/1/28 19:48
 * Project AwakeningEra2
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;

    @Autowired
    UserRoleMapper userRoleMapper;

    private static BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Transactional
    @RequestMapping("/register")
    public ResponseData register(@RequestParam("username")String username, @RequestParam("password")String password,
                                 @RequestParam("email")String email, @RequestParam("phonenumber")String phonenumber){
        ResponseData responseData = new ResponseData();
        responseData.setCode(ResponseCode.SUCCESS);
        try{

            User user = new User(username,bCryptPasswordEncoder.encode(password),email,phonenumber);
            userMapper.insert(user);
            Long userid =user.getUserid();
            UserRole userRole = new UserRole();
            userRole.setUserid(userid);
            userRole.setRoleid(2L);
            userRoleMapper.insert(userRole);

            responseData.getData().put("msg", "success");
        }catch (Exception e){
            responseData.setCode(ResponseCode.FAIL);
        }

        return responseData;
    }
}
